﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using YunLuPos.DB.Service;
using YunLuPos.Entity;
using YunLuPos.Entity.Constant;
using YunLuPos.Payment;
using YunLuPos.Printer;

namespace YunLuPos.SellView
{
    public partial class SellPayForm : UIEditForm
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SellPayForm));
        private PayTypeService payTypeService = new PayTypeService();
        private SaleOrderAccountService accountService = new SaleOrderAccountService();
        private SaleOrderService orderService = new SaleOrderService();
        private FileKeyBoardService boardService = FileKeyBoardService.getService();
        private PayType currentPayType = null;
        public PaymentState state = null; //当前单据支付状态数据
        private SaleOrder order = null;
        public SellPayForm()
        {
            InitializeComponent();
        }

        public SellPayForm(SaleOrder order)
        {
            InitializeComponent();
            this.order = order;
        }

        private void SellPayForm_Load(object sender, EventArgs e)
        {
            this.payedGrid.AutoGenerateColumns = false;
            this.payTypeGrid.AutoGenerateColumns = false;
            this.payedGrid.ClearSelection();
            this.ActiveControl = this.amountInput;
            this.amountInput.SelectAll();
            List<PayType> list = null;
            if (SaleOrderType.SALE.ToString().Equals(order.orderType))
            {
                list = payTypeService.list();
            }
            else if (SaleOrderType.REJECT.ToString().Equals(order.orderType))
            {
                list = payTypeService.listRefundType();
            }
            this.payTypeGrid.DataSource = list;
        }


        /**
        * 刷新显示支付状态
        * */
        public void displayState()
        {
            Console.WriteLine("displayState");
            state = orderService.getPaymentState(order.orderCode, currentPayType.isLessCent);
            this.payAmount.Text = state.needPay.ToString("F2");
            this.payedAmount.Text = state.payed.ToString("F2");
            this.lessAmount.Text = state.less.ToString("F2");
            this.lessAmount.Text = state.less.ToString("F2");
            this.amountInput.Text = state.less.ToString("F2");
            this.amountInput.SelectAll();
            this.payedGrid.DataSource = accountService.list(order.orderCode);
            //客显显示应收金额
            try
            {
                //PrinterManager.getDisplayer().write("CLR");
                PrinterManager.getDisplayer().write(String.Format("{0:F2}",state.needPay),2);
            }
            catch (Exception ex)
            {
                logger.Error("客显错误", ex);
            }
        }

        private void amountInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 如果输入的不是退格和数字，则屏蔽输入
            if (!(e.KeyChar == 8 || e.KeyChar == 46 || (e.KeyChar >= 48 && e.KeyChar <= 57)))
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 更新支付按键由原回车键更新为自定义默认回车键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SellPayForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                this.moveUp();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Down)
            {
                this.moveDown();
                e.Handled = true;
            }else
            {
                KeyBoard keys = boardService.getByKeyCode("支付窗体",e.KeyCode.ToString());
                if(keys != null && "Pay".Equals(keys.commandKey))
                {
                    //自定义按键
                    pay();
                }else
                {
                    //默认回车
                    if (e.KeyCode == Keys.Enter)
                    {
                        pay();
                    }
                }
            }
            
        }

        /**
         * 下移选中行
         * 到最后一行停止
         * */
        public void moveUp()
        {
            if (payTypeGrid.RowCount == 0)
            {
                return;
            }
            if (payTypeGrid.CurrentRow.Index > 0)
            {
                int moveRow = payTypeGrid.CurrentRow.Index - 1;
                payTypeGrid.CurrentCell = payTypeGrid.Rows[moveRow].Cells[0];
            }
        }

        /**
        * 上一选中行
        * 到第一行停止
        * */
        public void moveDown()
        {
            if (payTypeGrid.RowCount == 0)
            {
                return;
            }
            if (payTypeGrid.CurrentRow.Index < payTypeGrid.RowCount - 1)
            {
                int moveRow = payTypeGrid.CurrentRow.Index + 1;
                payTypeGrid.CurrentCell = payTypeGrid.Rows[moveRow].Cells[0];
            }
        }

        private void payTypeGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            if (payTypeGrid.CurrentRow != null)
            {
                PayType paytype = payTypeGrid.CurrentRow.DataBoundItem as PayType;
                if (!paytype.Equals(currentPayType))
                {
                    this.message.Text = "*";
                    currentPayType = paytype;
                    displayState();
                }
            }
        }


        /***
        * 调用支付
        * */
        void pay()
        {
            if(state.needPay <= 0)
            {
                this.ShowInfoDialog("应收金额为0不允许结账",this.Style);
                return;
            }
            //检查是否支付完成
            if (state.less < 0)
            {
                return;
            }
            if (state.less == 0)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
                return;
            }

            //检查输入金额
            String amtStr = this.amountInput.Text;
            if(amtStr == null || "".Equals(amtStr))
            {
                return;
            }
            Double inputAmount = 0;
            try
            {
                inputAmount = Math.Round(Double.Parse(amtStr), 2);
                if(inputAmount >= 99999)
                {
                    displayState();
                    this.message.Text = "输入金额不能大于99999";
                    return;
                }
            }
            catch
            {
                return;
            }
            if (inputAmount == 0)
            {
                return;
            }
            //检查溢收
            if (SaleOrderType.SALE.ToString().Equals(order.orderType))
            {
                if (!"1".Equals(currentPayType.isOverFlow))
                {
                    Console.WriteLine(inputAmount);
                    Console.WriteLine(state.less);
                    if (Double.Parse(inputAmount.ToString("f2")) > Double.Parse(state.less.ToString("f2")))
                    {
                        this.message.Text = "【" + currentPayType.payTypeName + "】不允许溢收";
                        return;
                    }
                }
            }
            else if (SaleOrderType.REJECT.ToString().Equals(order.orderType))
            {
                if (inputAmount > Math.Round(state.less,2))
                {
                    this.message.Text = "退货不允许溢退";
                    return;
                }
            }

            DataGridViewCell c = this.payTypeGrid.CurrentCell;
            //执行支付
            ResultMessage rm = PaymentManager.doPay(order, currentPayType, state, inputAmount);
            if (ResultMessage.SUCCESS.Equals(rm.Code))
            {
                displayState();
                this.message.Text = "*";
            }
            else
            {
                this.message.Text = rm.ErrorMessage;
            }
            this.payTypeGrid.CurrentCell = c;
        }
        /// <summary>
        /// 界面渲染完成后全选输入框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SellPayForm_Shown(object sender, EventArgs e)
        {
            this.amountInput.SelectAll();
        }
    }
}
